<?php
namespace hema\delivery\engine;

use app\common\model\Setting;

/**
 * 达达配送
 * 线上域名：newopen.imdada.cn
 * 测试域名：newopen.qa.imdada.cn
 * 测试门店编号：11047059
 * 测试商户编号：73753
*/
class Dada extends Basics
{
	private $callback_url = 'task/delivery/dada';	//回调URL（查看回调说明）
	private $businessParams = '';//请求数据（body内容）

    /**
     * 构造函数
    */
    public function __construct($order){
		$config = Setting::getItem('webdelivery',0)['dada'];
		parent::__construct($config, $order);
    }
	
	/**
     * 预发布订单创建
	*/
	public function preOrder()
	{
		$order = $this->order;
		$user = $order['address'];//收货人信息
		$user_location = explode(',',$user['location']);//拆分收货人定位经纬度
		$shop = $order['shop'];//发货门店
		$shop_location = explode(',',$shop['coordinate']);//拆分门店定位经纬度
		$post_data = [
			'shop_no' => $shop['dada_shop_id'],//是 门店编号
			'origin_id' => $order['order_no'],//是 第三方订单ID
			'city_code' => $this->getCiytCode($shop['city']),//是 订单所在城市的code
			'cargo_price' => $order['pay_price'],//是 订单金额
			'is_prepay' => 0,//是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
			'receiver_name' => $user['name'],//是 收货人姓名
			'receiver_address' => $user['detail'],//是 收货人地址
			'callback' => base_url() . $this->callback_url,//是 回调URL
			'receiver_lat' => $user_location[0], //否 收货人地址纬度
			'receiver_lng' => $user_location[1],//否 收货人地址经度
			'receiver_phone' => $user['phone'],//否 收货人手机号
			//'tips' => 0,//否 小费（单位：元，精确小数点后一位）
			'info' => $order['message'],//否 订单备注
			//'cargo_type' => 1,//否 订单商品类型：食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29,火锅-51,其他-5
			'cargo_weight' => 0.1,//是	订单重量（单位：Kg）
			//'origin_mark_no' => '河马云店',//否	订单来源编号
			//'is_use_insurance' => 0,//是否使用保价费（0：不使用保价，1：使用保价； 同时，请确保填写了订单金额（cargo_price））
		];
		$this->businessParams = json_encode($post_data,JSON_UNESCAPED_UNICODE);
		$post_data = $this->bulidRequestParams();
		$result = $this->getHttpRequestWithPost($post_data,'/api/order/queryDeliverFee');
		if($result['status'] == 'success'){
			return [
				'delivery_time' => '30分钟', //预计送达时间
				'delivery_distance' => (int)$result['result']['distance'] . '米', //配送距离
				'delivery_price' => '￥' . $result['result']['fee'] . '元', //配送费用
				'delivery_no' => $result['result']['deliveryNo'], //配送单号
				'dada' => $result
			];
		}
		$this->error = $result['msg'];
		return false;
	}

	/**
     * 创建订单 - 查询运费后发单接口
	*/
	public function addOrder($data = [])
	{
		$post_data = [
			'deliveryNo' => $data['delivery_no']//是 平台订单编号
		];
		$this->businessParams = json_encode($post_data,JSON_UNESCAPED_UNICODE);
		$post_data = $this->bulidRequestParams();
		$result = $this->getHttpRequestWithPost($post_data,'/api/order/addAfterQuery');
		if($result['status'] == 'success'){
			return $result;
		}
		$this->error = $result['msg'];
		return false;
	}

	/**
     * 取消订单
	*/
	public function cancelOrder($order_no = '')
	{
		$post_data = [
			'order_id' => $order_no,//第三方订单编号
			'cancel_reason_id' => 4, //取消原因ID
			//'cancel_reason' => ''//否	取消原因(当取消原因ID为其他时，此字段必填)
		];
		/*
		取消原因ID
		1	没有配送员接单
		2	配送员没来取货
		3	配送员态度太差
		4	顾客取消订单
		5	订单填写错误
		34	配送员让我取消此单
		35	配送员不愿上门取货
		36	我不需要配送了
		37	配送员以各种理由表示无法完成订单
		10000	其他
		 */
		$this->businessParams = json_encode($post_data,JSON_UNESCAPED_UNICODE);
		$post_data = $this->bulidRequestParams();
		$result = $this->getHttpRequestWithPost($post_data,'/api/order/formalCancel');
		if($result['status'] == 'success'){
			return $result;
		}
		$this->error = $result['msg'];
		return false;
	}
	
	/**
     * 获取城市编码
     */
	private function getCiytCode($city)
	{
		$city = str_replace('市','',$city);
		$this->businessParams = '';
		$post_data = $this->bulidRequestParams();
		$post_data['app_secret'] = $this->config['app_secret'];
		$result = $this->getHttpRequestWithPost($post_data,'/api/cityCode/list');
		$code = '';
		for($n=0;$n<sizeof($result['result']);$n++){
			if($result['result'][$n]['cityName'] == $city){
				$code = $result['result'][$n]['cityCode'];
				break;
			}
		}
		return $code;
	}

    /**
     * 发送请求,POST
     * @param $url 指定URL完整路径地址
     * @param $data 请求的数据
     */
    private function getHttpRequestWithPost($data,$url)
    {
		$data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $url = $this->config['api_url'] . $url;
        // json
        $headers = array(
            'Content-Type: application/json',
        );
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 3);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $resp = curl_exec($curl);
        //var_dump(curl_error($curl));//如果在执行curl的过程中出现异常，可以打开此开关查看异常内容。
        $info = curl_getinfo($curl);
        curl_close($curl);
        if (isset($info['http_code']) && $info['http_code'] == 200) {
            return json_decode($resp, true);
        }
        return false;
    }
	
	/**
     * 构造请求数据
     * data:业务参数，json字符串
     */
    private function bulidRequestParams()
    {
        $requestParams['app_key'] = $this->config['app_key']; //应用Key，对应开发者账号中的app_key
        $requestParams['body'] = $this->businessParams; //业务参数，JSON字符串
        $requestParams['format'] = 'json'; //请求格式，暂时只支持json
        $requestParams['source_id'] = $this->config['source_id']; //商户编号,测试环境默认为：73753
        $requestParams['timestamp'] = time(); //时间戳,单位秒
        $requestParams['v'] = '1.0'; //API版本
        $requestParams['signature'] = $this->_sign($requestParams); //签名Hash值
        return $requestParams;
    }

    /**
     * 签名生成signature
     */
    private function _sign($data){
		
        //1.升序排序
        ksort($data);
        //2.字符串拼接
        $args = "";
        foreach ($data as $key => $value) {
            $args.=$key.$value;
        }
        $args = $this->config['app_secret'] . $args . $this->config['app_secret'];
        //3.MD5签名,转为大写
        $sign = strtoupper(md5($args));
        return $sign;
    }
	
	
}
